package com.sinszm.common.exception;

import cn.hutool.core.util.HashUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.sinszm.common.Response;

/**
 * 公共异常处理
 *
 * @author chenjianbo
 */
public class ApiException extends RuntimeException {

    private final ApiError apiError;

    public ApiException() {
        this(SystemApiError.SYSTEM_ERROR_01);
    }

    public ApiException(ApiError apiError) {
        super(apiError.message());
        this.apiError = apiError;
    }

    public ApiException(String errCode, String errMsg) {
        super(errMsg == null ? "" : errMsg);
        this.apiError = new ApiError() {
            @Override
            public String getCode() {
                return StrUtil.isEmpty(errCode) ? "ERROR" : errCode.trim()
                        .replace(" ", "")
                        .replace("_", "-");
            }

            @Override
            public String getMessage() {
                return StrUtil.trimToEmpty(errMsg);
            }
        };
    }

    public ApiException(String errMsg) {
        super(errMsg == null ? "" : errMsg);
        this.apiError = new ApiError() {
            @Override
            public String getCode() {
                return "["+ HashUtil.oneByOneHash(
                        SecureUtil.md5(StrUtil.trimToEmpty(errMsg))
                )+"]";
            }

            @Override
            public String getMessage() {
                return StrUtil.trimToEmpty(errMsg);
            }
        };
    }

    private ApiError getApiError() {
        return apiError;
    }

    public ApiError apiError() {
        return this.getApiError();
    }

    @Override
    public String toString() {
        return Response.fail(
                this.getApiError(),
                super.getCause()
        ).toString();
    }
}
